package com.li.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.li.pojo.Permission;
import com.li.pojo.Role;
import com.li.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;
    /*
    用户登录调用的认证方法
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户是否存在
        User user = userService.findByUsername(username);
        if(user==null){
            return null;
        }

        //为用户进行授予权限与角色
        Set<GrantedAuthority> set=new HashSet<GrantedAuthority>();
        //遍历角色
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //授予角色
            set.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //授权
                set.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username, user.getPassword(), set);
        return userDetails;
    }
}
